package com.cyy.aop;

import com.cyy.utils.Common;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 针对appium自动化的处理
 * 1.出现失败用例打印错误信息
 * 2. 把错误测试步骤的截屏写入report
 * 3. 每个测试步骤，都app的性能信息，写入测试报告
 */
@Aspect
@Component
@Slf4j
public class AppiumAspect {

    @Autowired
    Common common;

    @Pointcut("execution(public * com.cyy.service.AppiumService.*(..)))")
    public void appiumAspect() {
    }

    @Before("appiumAspect()")
    public void doBefore(JoinPoint joinPoint) {
        common.sleep(500);
        log.info(method(joinPoint));
    }

    @After("appiumAspect()")
    public void doAfter(JoinPoint joinPoint) {
    }

    //@AfterThrowing(pointcut = "controllerLog() || uiControllerLog()", throwing = "ex")
    @AfterThrowing(pointcut = "appiumAspect()", throwing = "ex")
    public void doAfterThrowing(JoinPoint joinPoint, Exception ex) {
        log.error(method(joinPoint));
        log.error(ex.getMessage());
    }

    private String method(JoinPoint point) {
        String methodName = point.getSignature().getName();
        List<Object> args = Arrays.asList(point.getArgs());
        return String.format("%s(%s)", methodName, StringUtils.join(args.toArray(), ","));
    }

}
